package com.yfore.jfinal.pdf.plugin;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;

import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import com.itextpdf.text.pdf.BaseFont;
import com.jfinal.kit.PathKit;

import freemarker.template.Configuration;
import freemarker.template.Template;

public class PdfKit {
	private static final String HTML = "/template/template_freemarker_fs.html";
	private static final String FONT = "/simhei.ttf";
	// replace("\\","/")把文件路径改为统一/符号
	private static final String LOGO_PATH = "file:///" + PathKit.getRootClassPath().replace("\\", "/")
			+ "/template/logo.png";
	private static final String pdfUrl = "D:/System Files/Desktop/e-policy.pdf";
	private static Configuration freemarkerCfg = null;

	static {
		freemarkerCfg = new Configuration();
		// freemarker的模板目录
		try {
			freemarkerCfg.setDirectoryForTemplateLoading(new File(PathKit.getRootClassPath() + "/"));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static String freeMarkerRender(Map<String, Object> data) {
		Writer out = new StringWriter();// 准备好一个输出的对象
		try {
			Template template = freemarkerCfg.getTemplate(HTML, "UTF-8");// 获取模板,并设置编码方式
			// 合并数据模型与模板
			template.process(data, out); // 将合并后的数据和模板写入到流中，这里使用的字符流
			out.flush();// 强制性清空缓冲区的内容
			return out.toString();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				out.close();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return null;
	}

	public static void createPdf(String content) throws PdfCreateException {
		try {
			File pdfFile = new File(pdfUrl);//设置文件流地址
			OutputStream os = new FileOutputStream(pdfFile);// 将pdf文件转为文件流输出
			ITextRenderer render = new ITextRenderer();// 将HTML渲染PDF
			ITextFontResolver fontResolver = render.getFontResolver();// 设置渲染的字体
			fontResolver.addFont(FONT, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
			// 解析html生成pdf
			render.setDocumentFromString(content);
			// 解决图片相对路径的问题
			render.getSharedContext().setBaseURL(LOGO_PATH);
			render.layout();
			render.createPDF(os);
		} catch (Exception e) {
			throw new PdfCreateException("创建PDF错误！", e);
		}
	}
}